package com.taptech.doufu.ui.view.drawcircle;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Message;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.taptech.doufu.ui.activity.UserDetailActivity;
import com.taptech.doufu.util.ScreenUtil2;
import com.taptech.doufu.util.BitmapUtil;
import com.taptech.doufu.util.TextUtil;
import com.taptech.doufu.R;
import com.taptech.doufu.ui.activity.NewOthersPersonalActivity;
import com.taptech.doufu.bean.ComuBriefBean;
import com.taptech.doufu.bean.HomeTopBean;
import com.taptech.doufu.bean.ImageBean;
import com.taptech.doufu.bean.MineAbstractBean;
import com.taptech.doufu.bean.MineTopicBean;
import com.taptech.doufu.constant.Constant;
import com.taptech.doufu.listener.HttpResponseListener;
import com.taptech.doufu.bean.personalcenter.PersonalCardInfo;
import com.taptech.doufu.ui.viewholder.personalcenter.BaseAdapterViewHolder;
import com.taptech.doufu.services.personalcenter.AccountService;
import com.taptech.doufu.ui.view.personalcenter.ContentTagsViewGroup;
import com.taptech.doufu.ui.view.personalcenter.NewMyCollectView;
import com.taptech.doufu.services.UGCMainService;
import com.taptech.doufu.util.DiaobaoUtil;
import com.taptech.doufu.util.GlideUtil;
import com.taptech.doufu.util.ImageManager;
import com.taptech.doufu.util.TagsUtil;
import com.taptech.doufu.net.httputils.HttpResponseObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by lsy on 2015/9/29.
 */
public class TopicRecyclerViewHolder extends BaseRecyclerViewViewHolder implements View.OnClickListener, HttpResponseListener, View.OnLongClickListener
{

    // 总数据

    MineTopicBean bean;
    Context mContext;
    public TextView subjectName;
    public TextView subjectDes;
    public TextView subjectNoImgDes;
    public RelativeLayout bottomLayout;
    public TextView subjectSource;
    public LinearLayout imagegropLaoyout;
    private Bitmap defaultBitmap = null;
    public ImageView contentImage1, contentImage2, contentImage3;
    public TextView praiseMember;
    public TextView praiseMemberSumTextView;
    public TextView praiseCounts;
    public ImageView praiseIcon;
    public RelativeLayout showPraiseMem;

    public ImageView mAuthorImg, medalImg;
    public TextView mAuthorName;
    public TextView creatTime;
    public TextView mReadTimes;
    public TextView mElite;
    public TextView commentCount;
    int width, space, rightSpace;

    protected HomeTopBean onClickBean;
    protected ComuBriefBean comuBrief;
    protected ImageBean images[];
    protected int circleclass;
    // 点赞
    protected LinearLayout praisePressLayout;
    protected boolean hasBeenPraised;
    protected Drawable praiseNomal, praisePress;
    protected Animation mScaleBigAni;
    protected Animation mScaleSmallAni;
    protected int mPraiseCount;
    protected List<String> nameList;

    protected LinearLayout itemClickView;
    protected TextView mDeleteBtn;

    protected ContentTagsViewGroup tagGroupView;
    private int mPositon;

    public TopicRecyclerViewHolder(Context context, View convertView)
    {
        super(context, convertView);
        mContext = context;
        if (width == 0)
        {
            space = ScreenUtil2.dip2px(6);
            rightSpace = ScreenUtil2.dip2px(8);

            int macthWidth = ScreenUtil2.SCREEN_PX_WIDTH - space * 3 - 2 * rightSpace;
            width = macthWidth / 3;
        }
        // TODO Auto-generated method stub
        mDeleteBtn = (TextView) convertView.findViewById(R.id.delete_item_btn);
        itemClickView = (LinearLayout) convertView.findViewById(R.id.topic_backgroud_layout);
        subjectDes = (TextView) convertView.findViewById(R.id.home_item_subject_des);
        subjectNoImgDes = (TextView) convertView.findViewById(R.id.home_contents_item_no_img_des);
        bottomLayout = (RelativeLayout) convertView.findViewById(R.id.home_item_subject_bottom_layout);
        subjectSource = (TextView) convertView.findViewById(R.id.home_item_subject_circle_source);
        commentCount = (TextView) convertView.findViewById(R.id.home_item_subject_circle_chatcount);
        // subjectReadTimes = (TextView) convertView
        // .findViewById(R.id.home_contents_item_subject_read_times);
        praiseMember = (TextView) convertView.findViewById(R.id.home_contents_item_praise_member);
        praiseMemberSumTextView = (TextView) convertView.findViewById(R.id.home_contents_item_praise_sum);
        praiseCounts = (TextView) convertView.findViewById(R.id.home_contents_item_praise_counts);
        praiseIcon = (ImageView) convertView.findViewById(R.id.home_contents_item_praise_icon);
        praisePressLayout = (LinearLayout) convertView.findViewById(R.id.home_contents_item_praise_layout);
        showPraiseMem = (RelativeLayout) convertView.findViewById(R.id.home_contents_layout_show_praisemember);

        imagegropLaoyout = (LinearLayout) convertView.findViewById(R.id.home_item_subject_image_group1);
        contentImage1 = (ImageView) convertView.findViewById(R.id.home_item_subject_imgge1);
        contentImage2 = (ImageView) convertView.findViewById(R.id.home_item_subject_imgge2);
        contentImage3 = (ImageView) convertView.findViewById(R.id.home_item_subject_imgge3);

        mAuthorImg = (ImageView) convertView.findViewById(R.id.home_item_subject_authorimg);
        medalImg = (ImageView) convertView.findViewById(R.id.home_item_subject_medal);

        mAuthorName = (TextView) convertView.findViewById(R.id.home_item_subject_username);
        creatTime = (TextView) convertView.findViewById(R.id.home_item_subject_time);
        mReadTimes = (TextView) convertView.findViewById(R.id.home_item_subject_readtimes);
        mElite = (TextView) convertView.findViewById(R.id.home_item_topic_is_elite);
        LinearLayout.LayoutParams im_lp = new LinearLayout.LayoutParams(width, width);
        im_lp.setMargins(space, 0, 0, 0);
        contentImage1.setLayoutParams(im_lp);
        contentImage2.setLayoutParams(im_lp);
        contentImage3.setLayoutParams(im_lp);
        tagGroupView = (ContentTagsViewGroup) convertView.findViewById(R.id.topic_item_tag);
    }

    @Override
    public void setViewHolderChildViewContent(MineAbstractBean tempbean, int position)
    {
        bean = (MineTopicBean) tempbean;
        // TODO Auto-generated method stub
        if (bean == null)
        {
            return;
        }
        mPositon = position;
        if (mDeleteBtn != null)
        {
            mDeleteBtn.setOnClickListener(this);
        }

        // 查看详情
        itemClickView.setOnClickListener(this);
        itemClickView.setOnLongClickListener(this);
        // 点赞
        praisePressLayout.setOnClickListener(this);
        // 获取是否已赞过
        hasBeenPraised = false;
        if (bean.isHas_praise())
        {
            hasBeenPraised = true;
        } else
        {
            hasBeenPraised = false;
        }

        // 作者名
        if (bean.getUser().getName() != null)
        {
            mAuthorName.setText(bean.getUser().getName());
        }
        // 发布时间
        if (bean.getAdd_time() != null)
        {
            creatTime.setText(DiaobaoUtil.seconds2TimeString(Long.parseLong(bean.getAdd_time())));
        }
        // 来源圈子
        if (bean.getComuBrief() != null)
        {
            subjectSource.setText(bean.getComuBrief().getTitle());
        }
        // 是否加精
        if (bean.getElite() != null)
        {
            if (bean.getElite().equals("0"))
            {
                mElite.setVisibility(View.GONE);
            } else
            {
                mElite.setVisibility(View.VISIBLE);
            }
        }
        // 话题标题，标题是可以为空的
        if (bean.getTitle() == null || "".equals(bean.getTitle().trim()))
        {
            subjectDes.setVisibility(View.GONE);
        } else
        {
            subjectDes.setText(bean.getTitle());
            subjectDes.setVisibility(View.VISIBLE);
        }
        // 内容概要
        if (bean.getDes() == null || "".equals(bean.getDes()))
        {
            subjectNoImgDes.setVisibility(View.GONE);
        } else
        {
            subjectNoImgDes.setVisibility(View.VISIBLE);
            // 动态设置TextView显示行数
            TextUtil.handleTextView(subjectNoImgDes, bean.getDes(), 3);
        }
        // 浏览数显示
        if (bean.getRead_times() != null)
        {
            mReadTimes.setText(bean.getRead_times());
        }
        // 点赞
        praiseNomal = mContext.getResources().getDrawable(R.drawable.topic_praise_normal);
        praisePress = mContext.getResources().getDrawable(R.drawable.topic_praise_press);
        if (hasBeenPraised)
        {
            praiseIcon.setImageDrawable(praisePress);
        } else
        {
            praiseIcon.setImageDrawable(praiseNomal);
        }
        // 赞数
        mPraiseCount = Integer.valueOf(bean.getPraise_times());
        if (mPraiseCount == 0)
        {
            showPraiseMem.setVisibility(View.GONE);
        } else
        {
            showPraiseMem.setVisibility(View.VISIBLE);
        }
        if (bean.getPraise_times() != null)
        {
            praiseCounts.setText(bean.getPraise_times());
            if (bean.getPraise_times().equals("0"))
            {
                praiseCounts.setVisibility(View.INVISIBLE);
            } else
            {
                praiseCounts.setVisibility(View.VISIBLE);
            }
        }
        // 评论数
        if (bean.getComment_times() != null)
        {
            commentCount.setText(bean.getArticle_num());
        }

        // 设置头像
        if (bean.getUser() != null && bean.getUser().getIcon() != null)
        {
            Drawable userBitmap;
            // 默认头像
            userBitmap = mContext.getResources().getDrawable(R.drawable.default_user_portrait);
            mAuthorImg.setImageDrawable(userBitmap);
            GlideUtil.displayCircleImage(mAuthorImg, bean.getUser().getIcon());
        }
        // 显示内容图
        if (bean.getImages() != null)
        {
            images = bean.getImages();
            defaultBitmap = BitmapUtil.decodeSampledBitmapFromResource(mContext.getResources(), R.drawable.bg_home_photo_default, width, width);
            if (images.length > 0)
            {
                if (defaultBitmap != null)
                {
                    contentImage1.setImageBitmap(defaultBitmap);
                    contentImage2.setImageBitmap(defaultBitmap);
                    contentImage3.setImageBitmap(defaultBitmap);
                }
                imagegropLaoyout.setVisibility(View.VISIBLE);
                String imageUrl = images[0].getImgUrl();
                String imageUrl2 = null;
                String imageUrl3 = null;
                if (images.length == 1)
                {
                    imageUrl = images[0].getImgUrl();
                    contentImage2.setVisibility(View.INVISIBLE);
                    contentImage3.setVisibility(View.INVISIBLE);
                } else if (images.length == 2)
                {
                    imageUrl2 = images[1].getImgUrl();
                    contentImage3.setVisibility(View.INVISIBLE);
                    contentImage2.setVisibility(View.VISIBLE);
                } else
                {
                    imageUrl2 = images[1].getImgUrl();
                    imageUrl3 = images[2].getImgUrl();
                    contentImage3.setVisibility(View.VISIBLE);
                    contentImage2.setVisibility(View.VISIBLE);
                }
                if (defaultBitmap != null)
                {

                }
                if (imageUrl != null)
                {
                    ImageManager.displayImage(contentImage1, imageUrl, 0);
                    // imageLoader.displayImage(imageUrl,
                    // subjectHolder.contentImage1, objectOptions);
                }
                if (imageUrl2 != null)
                {
                    ImageManager.displayImage(contentImage2, imageUrl2, 0);
                    // imageLoader.displayImage(imageUrl2,
                    // subjectHolder.contentImage2, objectOptions);
                }
                if (imageUrl3 != null)
                {
                    ImageManager.displayImage(contentImage3, imageUrl3, 0);
                    // imageLoader.displayImage(imageUrl3,
                    // subjectHolder.contentImage3, objectOptions);
                }
            } else
            {
                imagegropLaoyout.setVisibility(View.GONE);
            }
        }
        // xxx赞过
        nameList = new ArrayList<String>();
        if (bean.getPraisers() != null && bean.getPraisers().length > 0)
        {
            for (PersonalCardInfo user : bean.getPraisers())
            {
                nameList.add(user.getNickname());
            }
            praiseMember.setText(getPraiseString(nameList));

        } else
        { //cp列表数据暂时隐藏点赞
            showPraiseMem.setVisibility(View.GONE);
        }
        if (mDeleteBtn != null)
        {
            if (bean.getSpecialType() == SPECIAL_TYPE_COLLECT)
            {
                mDeleteBtn.setVisibility(View.VISIBLE);
                mDeleteBtn.setText("取消收藏");
            } else if (bean.getSpecialType() == SPECIAL_TYPE_PERSONAL_DELETE && AccountService.getInstance().isUserSelf(bean.getUser().getUserId()))
            {
                mDeleteBtn.setVisibility(View.VISIBLE);
                mDeleteBtn.setText("删除");

            } else
            {
                if (bean.getUser() != null && AccountService.getInstance().isUserSelf(bean.getUser().getUserId()))
                {
                    mDeleteBtn.setVisibility(View.VISIBLE);
                } else
                {
                    mDeleteBtn.setVisibility(View.GONE);
                }
            }

        }
        if (bean.getTags() != null && bean.getTags().length > 0)
        {
            String[] tagStrings = TagsUtil.convertTagbeans2Strings(bean.getTags());
            tagGroupView.setVisibility(View.VISIBLE);
            tagGroupView.setTextTags(mContext, tagStrings);
        } else
        {
            tagGroupView.setVisibility(View.GONE);
        }
    }

    private String getPraiseString(List<String> userNames)
    {
        StringBuilder resultString = new StringBuilder();
        if (userNames == null)
        {
            return null;
        }
        if (userNames.size() > 2)
        {
            resultString.append(userNames.get(0)).append("、").append(userNames.get(1)).append("等").append(bean.getPraise_times()).append("人赞过");
        } else if (userNames.size() == 2)
        {
            resultString.append(userNames.get(0)).append("、").append(userNames.get(1)).append("赞过");
        } else if (userNames.size() == 1)
        {
            resultString.append(userNames.get(0)).append("赞过");
        } else
        {
            ;
        }
        return resultString.toString();
    }

    @Override
    public void handleResponse(int handleType, HttpResponseObject response)
    {

    }

    @Override
    public void onClick(View view)
    {
        switch (view.getId())
        {
            case R.id.home_contents_item_praise_layout:
                if (!AccountService.getInstance().isLogin())
                {
                    AccountService.getInstance().jumpToLogin();
                } else
                {
                    // 点赞
                    if (!hasBeenPraised)
                    {
                        praiseIcon.setImageDrawable(praisePress);
                        mPraiseCount += 1;
                        praiseCounts.setText(mPraiseCount + "");
                        praiseCounts.setVisibility(View.VISIBLE);
                        hasBeenPraised = true;
                        mScaleBigAni = new ScaleAnimation(1.0f, 2.0f, 1.0f, 2.0f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
                        mScaleBigAni.setDuration(300);
                        mScaleBigAni.setFillAfter(true);
                        mScaleSmallAni = new ScaleAnimation(2.0f, 1.0f, 2.0f, 1.0f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
                        mScaleSmallAni.setDuration(300);
                        mScaleSmallAni.setFillAfter(true);
                        mScaleBigAni.setAnimationListener(new Animation.AnimationListener()
                        {

                            @Override
                            public void onAnimationStart(Animation animation)
                            {
                            }

                            @Override
                            public void onAnimationRepeat(Animation animation)
                            {

                            }

                            @Override
                            public void onAnimationEnd(Animation animation)
                            {
                                praiseIcon.startAnimation(mScaleSmallAni);
                            }
                        });
                        praiseIcon.startAnimation(mScaleBigAni);
                        // 上传点赞信息
                        UGCMainService.getInstance().addPraiseUser(bean.getId(), this);
                        nameList.add(0, AccountService.getInstance().getBaseAccount().getNickname());
                        praiseMember.setText(getPraiseString(nameList));
                        showPraiseMem.setVisibility(View.VISIBLE);

                        // 取消点赞
                    } else
                    {
                        praiseIcon.setImageDrawable(praiseNomal);
                        mPraiseCount -= 1;
                        praiseCounts.setText(mPraiseCount + "");
                        if (mPraiseCount == 0)
                        {
                            praiseCounts.setVisibility(View.INVISIBLE);
                        }
                        hasBeenPraised = false;
                        // 上传点赞信息
                        UGCMainService.getInstance().delPraiseUser(bean.getId(), this);
                        int tempindex = nameList.indexOf(AccountService.getInstance().getBaseAccount().getNickname());
                        if (tempindex != -1)
                        {
                            nameList.remove(tempindex);
                        }
                        if (mPraiseCount == 0)
                        {
                            showPraiseMem.setVisibility(View.GONE);
                        }
                        praiseMember.setText(getPraiseString(nameList));

                    }
                }
                break;
            case R.id.home_item_subject_authorimg:
            {
                UserDetailActivity.Companion.startActivity(mContext,bean.getId());
                break;
            }
            case R.id.delete_item_btn:
                if (bean.getSpecialType() == SPECIAL_TYPE_COLLECT)
                {
                    Message message = new Message();
                    message.what = NewMyCollectView.DEL_COLLECT_ITEM_COMMAND;
                    Bundle bundle = new Bundle();
                    bundle.putString("id", bean.getId());
                    bundle.putInt("position", mPosition);
                    bundle.putString(Constant.OBJECT_TYPE, bean.getObject_type());
                    message.setData(bundle);
                    if (mHandler != null)
                    {
                        mHandler.sendMessage(message);
                    }
                } else if (bean.getSpecialType() == SPECIAL_TYPE_PERSONAL_DELETE && AccountService.getInstance().isUserSelf(bean.getUser().getUserId()))
                {
                    Message message = new Message();
                    message.what = BaseAdapterViewHolder.DELETE_TOPIC_ITEM;
                    Bundle bundle = new Bundle();
                    bundle.putString("id", bean.getId());
                    bundle.putInt("position", mPosition);
                    bundle.putString(Constant.OBJECT_TYPE, bean.getObject_type());
                    message.setData(bundle);
                    if (mHandler != null)
                    {
                        mHandler.sendMessage(message);
                    }
                }
                break;
        }
    }

    @Override
    public boolean onLongClick(View view)
    {

        if (bean.getSpecialType() == SPECIAL_TYPE_COLLECT)
        {
            Message message = new Message();
            message.what = NewMyCollectView.DEL_COLLECT_ITEM_COMMAND;
            Bundle bundle = new Bundle();
            bundle.putString("id", bean.getId());
            bundle.putInt("position", mPosition);
            bundle.putString(Constant.OBJECT_TYPE, bean.getObject_type());
            message.setData(bundle);
            if (mHandler != null)
            {
                mHandler.sendMessage(message);
            }
        } else if (bean.getSpecialType() == SPECIAL_TYPE_PERSONAL_DELETE && AccountService.getInstance().isUserSelf(bean.getUser().getUserId()))
        {
            Message message = new Message();
            message.what = BaseAdapterViewHolder.DELETE_TOPIC_ITEM;
            Bundle bundle = new Bundle();
            bundle.putString("id", bean.getId());
            bundle.putInt("position", mPosition);
            bundle.putString(Constant.OBJECT_TYPE, bean.getObject_type());
            message.setData(bundle);
            if (mHandler != null)
            {
                mHandler.sendMessage(message);
            }
        }
        return true;
    }
}
